import os
import ipaddress
import concurrent.futures
from config.settings import (
    ip_range_regex,
    cidr_regex)


#地址父类，生成address，存储所有处理过的地址
class Address:
    def __init__(self):
        self.address = set()  #生成集合存储所有地址并实现去重
#添加ip形式地址
    def process_ip(self, ip):
        self.address.add(ip)
#添加非ip形式地址
    def add_other_address(self, address):
        self.address.add(address)
#返回所有处理好的地址
    def get_addresses(self):
        return self.address

#重写父类，对ip分类处理
class Address_ip(Address):
    def __init__(self):
        super().__init__()

    def process_ip(self, ip):
        try:
            # 处理 CIDR 格式的 IP 地址 (例如 192.168.1.0/24)
            if "/" in ip:
                network = ipaddress.IPv4Network(ip, strict=False)
                for ip in network.hosts():
                    self.address.add(str(ip))  # 使用父类的 process_ip 方法将地址添加到集合中

            # 处理 IP 范围 (例如 192.168.1.1-192.168.1.5)
            elif "-" in ip:
                start, end = [ip.strip() for ip in ip.split('-')]
                start_num = self.ip_to_int(start)
                end_num = self.ip_to_int(end)
                # 生成 IP 范围中的所有 IP 地址
                for num in range(start_num, end_num + 1):
                    self.address.add(self.int_to_ip(num))  # 将地址转换为字符串并添加
            else:
                self.address.add(ip)  # 处理单个 IP 地址
        except Exception as e:
            print(f"Error while processing IP: {e}")
    #ip与整数之间形式转换
    def ip_to_int(self, ip):
        return int(ipaddress.IPv4Address(ip))
    def int_to_ip(self, num):
        return str(ipaddress.IPv4Address(num))

def process_line(line, address_all):
    line = line.strip()

    if line == '':
        return

    # 处理 CIDR 地址或 IP 范围
    if ip_range_regex.match(line) or cidr_regex.match(line):
        address_all.process_ip(line)
    else:
        # 其他格式的地址
        address_all.add_other_address(line)


def process_file(file_path, address_all):
    if not os.path.exists(file_path):
        print(f"Error: The file path '{file_path}' does not exist.")
        return

    # 使用线程池并发处理每一行
    with open(file_path, 'r') as file:
        with concurrent.futures.ThreadPoolExecutor() as executor:
            # 使用线程池处理每一行地址
            futures = [executor.submit(process_line, line, address_all) for line in file]
            # 等待所有任务完成
            concurrent.futures.wait(futures)

